package com.test.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.test.demo.entity.e.DataSourceProperties;
import com.test.demo.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.sql.DataSource;
import java.util.List;

/**
 * 数据源配置
 */
@Configuration
public class DataSourceConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private DataSourceService dataSourceService;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource(masterDataSource);
        // 添加主数据源
        dynamicDataSource.addDataSource(DataSourceType.MASTER.name(), masterDataSource);
        return dynamicDataSource;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // Spring 容器完全启动后，从数据库加载其他数据源配置
        try {
            List<DataSourceProperties> dataSourceList = dataSourceService.getAllEnabledDataSources();
            for (DataSourceProperties properties : dataSourceList) {
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setDriverClassName(properties.getDriverClassName());
                dataSource.setUrl(properties.getUrl());
                dataSource.setUsername(properties.getUsername());
                dataSource.setPassword(properties.getPassword());
                // 设置其他连接池属性
                dataSource.setInitialSize(5);
                dataSource.setMinIdle(10);
                dataSource.setMaxActive(20);

                dynamicDataSource.addDataSource(properties.getDatasourceKey(), dataSource);
            }
        } catch (Exception e) {
            // 记录错误但不影响启动
            e.printStackTrace();
        }
    }
} 